package cn.buk.tms.hotel.util;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.classic.methods.*;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.*;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.net.URLEncodedUtils;



import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * User: yfdai
 * Date: 14-5-25
 * Time: 下午11:26
 * 2017.3.30 9:40 yfdai
 * 根据HttpClient 4.5.3的提示，将过时的api去掉
 * @author yfdai
 */
public class HttpUtil extends BaseHttpClient {

//    private static Logger logger = Logger.getLogger(HttpUtil.class);

    public static CloseableHttpClient createHttpClient() {
        return createHttpClient(null, null);
    }

    public static String getUrl(String url, List<NameValuePair> params) {
        String uri  = url;
        if (params != null) {
          uri += URLEncodedUtils.format(params, StandardCharsets.UTF_8);
        }

//        logger.info(uri);

        CloseableHttpClient httpClient = createHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().build();

        HttpGet httpGet = new HttpGet(uri);
        httpGet.setConfig(requestConfig);

        httpGet.setHeader("Referer", "http://www.buk.cn/");

        return executeGet(httpClient, httpGet);
    }

    public static String executeGet(CloseableHttpClient httpClient, HttpGet httpGet) {
        String rs="";

        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            if (response.getCode() == HttpStatus.SC_OK) {
                rs = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                rs = EntityUtils.toString(response.getEntity(), "UTF-8");
//                logger.error(rs);
            }

            response.close();
        } catch (Exception e) {
//            logger.error(e.getMessage());
        }

        return rs;
    }

    public static String postUrl(final String url, final String body, final boolean isJson) {
        CloseableHttpClient httpClient = createHttpClient();

        RequestConfig requestConfig = RequestConfig.custom().build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (isJson) {
            httpPost.setHeader("Content-type", "application/json");
        }

        String rs = "";

        try {
            StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);

            System.out.println(response);

            if (response.getCode() == HttpStatus.SC_OK) {
                rs = EntityUtils.toString(response.getEntity(), "UTF-8");

                System.out.println(rs);
            }

            response.close();
        } catch (Exception e) {
//            logger.error(e.getMessage());
        }

        return rs;
    }

    public static String postUrl(final String url, List<NameValuePair> params) {
        CloseableHttpClient httpClient = createHttpClient();

        RequestConfig requestConfig = RequestConfig.custom().build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        String rs = "";

        try {
            //转化参数
            UrlEncodedFormEntity refe = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);

            //设置参数
            httpPost.setEntity(refe);

            CloseableHttpResponse response = httpClient.execute(httpPost);

            if (response.getCode() == HttpStatus.SC_OK) {
                rs = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }

            response.close();
        } catch (Exception e) {
//            logger.error(e.getMessage());
        }

        return rs;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
//        logger.debug(ip);

        return ip;
    }

    public static void sendResponse(HttpServletResponse response, String content) {
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw;
        try {
            pw = response.getWriter();
            pw.print(content);
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
